package com.demo.gateway.config;

import com.demo.gateway.filter.AuthFilter;
import com.demo.gateway.filter.RateLimitFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Gateway路由配置
 * 配置各个微服务的路由规则
 */
@Configuration
public class GatewayConfig {

    @Autowired
    private AuthFilter authFilter;

    @Autowired
    private RateLimitFilter rateLimitFilter;

    /**
     * 配置路由规则
     * @param builder 路由构建器
     * @return 路由定位器
     */
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                // 商品服务路由
                .route("product-service", r -> r
                        .path("/api/product/**")
                        .filters(f -> f
                                .filter(rateLimitFilter) // 添加限流过滤器
                                .stripPrefix(0)) // 不去除路径前缀
                        .uri("lb://product-service")) // 负载均衡到product-service
                
                // 订单服务路由
                .route("order-service", r -> r
                        .path("/api/order/**")
                        .filters(f -> f
                                .filter(authFilter) // 添加认证过滤器
                                .filter(rateLimitFilter) // 添加限流过滤器
                                .stripPrefix(0))
                        .uri("lb://order-service"))
                
                // 用户服务路由
                .route("user-service", r -> r
                        .path("/api/user/**")
                        .filters(f -> f
                                .filter(rateLimitFilter) // 添加限流过滤器
                                .stripPrefix(0))
                        .uri("lb://user-service"))
                
                // 定时任务服务路由（管理员接口）
                .route("job-service", r -> r
                        .path("/api/job/**")
                        .filters(f -> f
                                .filter(authFilter) // 添加认证过滤器
                                .stripPrefix(0))
                        .uri("lb://job-service"))
                
                // 秒杀专用路由（高优先级，特殊处理）
                .route("seckill-route", r -> r
                        .path("/api/seckill/**")
                        .filters(f -> f
                                .filter(rateLimitFilter) // 严格限流
                                .rewritePath("/api/seckill/(?<segment>.*)", "/api/product/${segment}"))
                        .uri("lb://product-service"))
                
                .build();
    }
}